from django.views import View
from ihome_project.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse, JsonResponse
from ihome_project.libs.yuntongxun.ccp_sms import CCP
import logging, json
logger = logging.getLogger('django')
import random
from celery_tasks.sms.tasks import ccp_send_sms_code

from apps.users.models import User

# Create your views here.
class ImageCodeView(View):
    '''返回图形验证码'''

    def get(self, request):
        '''
        生成图形验证码, 保存到redis中, 另外返回图片
        :param request:请求对象
        :param uuid:浏览器端生成的唯一id
        :return:一个图片
        '''
        uuid = request.GET.get('cur')
        # pre = request.GET.get('pre')

        # 1.调用工具 captcha
        text, image = captcha.generate_captcha()
        print(text)

        # 2.连接redis, 获取连接对象
        conn = get_redis_connection('verify_code')

        # 3.利用链接对象, 保存数据到 redis, 使用 setex 函数
        # redis_conn.setex('<key>', '<expire>', '<value>')
        conn.setex('img_%s' % uuid, 300, text)

        # 4.返回(图片)
        return HttpResponse(image,
                            content_type='image/jpg')


class SMSCodeView(View):

    def post(self, request):

        # 1 接收参数
        dict = json.loads(request.body.decode())

        mobile = dict.get('mobile')
        id = dict.get('id')
        text = dict.get('text')
        # 判断用户是否已经组成
        if User.objects.filter(mobile=mobile):
            return JsonResponse({
                'errno':'4003',
                'errmsg':'手机号码重复注册1'
            })


        # 2 校验参数
        if not all([mobile, text, id]):
            return JsonResponse({'errno': '4004',
                                 'errmsg': '缺少必传参数'})
        # 3 创建连接redis对象
        redis_conn = get_redis_connection('verify_code')

        # 4 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % id)
        if image_code_server is None:
            return JsonResponse({'errno': '4004',
                                 'errmsg': '图片验证码过期'})
        # 5 删除图形验证码,避免恶意测试
        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.info(e)


        # 6 对比
        image_code_server = image_code_server.decode()
        if text.lower() != image_code_server.lower():
            return JsonResponse({'errno': '4004',
                                 'errmsg': '输入的图形码出错'})

        if redis_conn.get('sms_flag_%s' % mobile):
            return JsonResponse({
                'errno': 4004,
                'errmsg': '不要频繁发送短信'
            })

        # 7 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)
        try:
            p1 = redis_conn.pipeline()
            p1.setex('sms_flag_%s' % mobile, 60, 1)
            # 8 保存短信验证码,有效期300s
            p1.setex('sms_%s' % mobile, 300, sms_code)
            p1.execute()
        except Exception as e:
            return JsonResponse({
                'errno': 4004,
                'errmsg': '保存验证码失败'
            })

        # 9 发送短信验证码
        # CCP().send_template_sms('mobile', ['sms_code', 5], 1)

        ccp_send_sms_code.delay(mobile, sms_code)
        # 10 响应
        return JsonResponse({'errno': '0',
                             'errmsg': '发送成功'})